﻿using NxStoreManage;

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace LengthAiCalculate
{
    public partial class AddCutGroupItem : BaseForm
    {
        public AddCutGroupItem()
        {
            InitializeComponent();
            SetDataGridDefault(dataGridView1, rowHeadersVisible: false, autoGenerateColumns: true);
        }

        public Action SucAction;
        private string outKeyCode = "", gglb = "";

        public void SetInfo(string outKeyCode, string zzph, string steelName, string sizeName, string gglb, string length)
        {
            this.outKeyCode = outKeyCode.Trim();
            label2.Text = zzph.Trim();
            label4.Text = steelName.Trim();
            label6.Text = sizeName.Trim();
            this.gglb = gglb.Trim();
            if (length != "0")
            {
                textBox1.Text = length;
                textBox1.Enabled = false;
                textBox2.Focus();
            }
            else
            {
                textBox1.Text = "";
                textBox1.Enabled = true;
                textBox1.Focus();
            }
        }

        private void AddCutGroupItem_Load(object sender, EventArgs e)
        {
        }

        private DataTable dt = new System.Data.DataTable();
        private decimal length = 0;
        private int num = 0;

        private void button2_Click(object sender, EventArgs e)
        {
            if (!dt.Columns.Contains("长度")) { dt.Columns.Add("长度", typeof(decimal)); }
            if (!dt.Columns.Contains("支数")) { dt.Columns.Add("支数", typeof(int)); }
            length = 0;
            num = 0;
            if (!decimal.TryParse(textBox1.Text.Trim(), out length) || length <= 0 || length > 30)
            {
                MessageBox.Show("请输入正确的长度");
                return;
            }
            if (!int.TryParse(textBox2.Text.Trim(), out num) || num == 0)
            {
                MessageBox.Show("请输入正确的支数,可以为负数，但不能为0！");
                return;
            }
            var row = dt.Select("长度=" + length);
            if (row.Length > 0)
            {
                row[0]["支数"] = Convert.ToInt32(row[0]["支数"]) + num;
            }
            else
            {
                dt.Rows.Add(length, num);
            }
            dataGridView1.DataSource = dt;
            dataGridView1.Columns[0].Width = (dataGridView1.Width - 15) / 2;
            dataGridView1.Columns[1].Width = (dataGridView1.Width - 15) / 2;
        }

        private void AddCutGroupItem_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dataGridView1.Rows.Count > 0 && MessageBox.Show("当前数据未保存，退出后数据将丢失，是否退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            dt.Clear();
        }

        private List<string> listSql = new List<string>();

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            double totalNum = 0;
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                double.TryParse(item.Cells["支数"].Value.ToString(), out double n);
                totalNum += n;
            }
            label12.Text = totalNum.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listSql.Clear();
            listSql.Add("DECLARE @itemKey CHAR(32);");
            string itemKey = "";
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                itemKey = Guid.NewGuid().ToString("N");
                listSql.Add($@"SELECT @itemKey = itemKey
                    FROM [PM.ManualManufactureResultGroupZZPH]
                    WHERE outKeyCode = '{outKeyCode}'
                          AND zzph = '{label2.Text}'
                          AND steelClassName = '{label4.Text}'
                          AND sizeName = '{label6.Text}'
                          AND [length] = {item.Cells["长度"].Value}*1000;
                    IF @itemKey IS NULL
                    BEGIN
                        SET @itemKey = '{itemKey}';
                        INSERT INTO [PM.ManualManufactureResultGroupZZPH]
                        (
                            zzph,
                            gglb,
                            steelClassName,
                            sizeName,
                            [length],
                            cutNum,
                            outKeyCode,
                            packNum,
                            inStoreNum,
                            itemKey
                        )
                        VALUES
                        ('{label2.Text}', '{gglb}', '{label4.Text}', '{label6.Text}',  {item.Cells["长度"].Value}*1000, {item.Cells["支数"].Value}, '{outKeyCode}', 0, 0, @itemKey);
                    END;
                    ELSE
                        UPDATE [PM.ManualManufactureResultGroupZZPH]
                        SET cutNum = ISNULL(cutNum, 0) + {item.Cells["支数"].Value}
                        WHERE itemKey = @itemKey;
                    INSERT INTO [PM.ManualManufactureResultGroupZZPHItem]
                    (
                        itemKey,
                        cutNum,
                        createUser,
                        createDate,createType
                    )
                    VALUES
                    (@itemKey,{item.Cells["支数"].Value}, '{LoginUser.LoginUserName}', GETDATE(),1);SET @itemKey = NULL");
            }
            if (listSql.Any())
            {
                var suc = nxsqlHelper.ExcuteSql(sqlList: listSql);
                if (suc > 0)
                {
                    SucAction?.Invoke();
                    MessageBox.Show("保存成功" + suc + "条");
                    dt.Clear();
                    dataGridView1.DataSource = dt;
                }
                else
                {
                    MessageBox.Show("保存失败，请稍后再试");
                }
            }
            else
            {
                ShowError("没有可保存的数据");
            }
        }
    }
}